package com.my.socket.nio.v7;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;

public class AcceptTask implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(AcceptTask.class);

    private Selector acceptSelector;
    private Selector[] readWriteSelectors;
    private int readWriteSelectorsCount;
    private ServerSocketChannel serverSocketChannel;

    public AcceptTask(ServerSocketChannel serverSocketChannel, Selector acceptSelector, Selector[] readWriteSelectors) throws Exception {
        this.serverSocketChannel = serverSocketChannel;
        this.acceptSelector = acceptSelector;
        this.readWriteSelectors = readWriteSelectors;
        this.readWriteSelectorsCount = readWriteSelectors.length;
        this.serverSocketChannel.register(this.acceptSelector, SelectionKey.OP_ACCEPT);
    }

    @Override
    public void run() {
        try {
            Random random = new Random();
            while (true) {
                int select = this.acceptSelector.select();
                if (select == 0) {
                    continue;
                }
                LOGGER.info("{} event(s) incoming...", select);

                Set<SelectionKey> selectionKeys = this.acceptSelector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();

                    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    int position = random.nextInt(this.readWriteSelectorsCount);
                    socketChannel.register(this.readWriteSelectors[position].wakeup(), SelectionKey.OP_READ);
                    LOGGER.info("incoming socket: {}", socketChannel);
                }
            }
        } catch (Exception e) {
            LOGGER.error("exception caught, the error is {}", e.getMessage());
        }
    }
}
